package com.atguigu.tingshu.album.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class TrackListener {

    @Autowired
    private AlbumStatMapper albumStatMapper;

    @Autowired
    private TrackStatMapper trackStatMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(RabbitConstant.STAT_UPDATE_QUEUE),
            exchange = @Exchange(value = RabbitConstant.STAT_UPDATE_EXCHANGE, type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
            key = {RabbitConstant.STAT_UPDATE_RK}
    ))
    public void updateStat(String message, Message msg, Channel channel) {
        TrackStatMqVo statMqVo = JSON.parseObject(message, TrackStatMqVo.class);
        try {
            // 更新专辑播放量
            albumStatMapper.updatePlayStatNum(statMqVo.getAlbumId());
            // 更新声音播放量
            trackStatMapper.updatePlayStatNum(statMqVo.getTrackId());
            // 手动ack
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                // redelivered == true代表该消息已经消费过，丢弃消息，如果为false，代表消息未消费过，重新归队再次消费
                if (msg.getMessageProperties().isRedelivered()) {
                    channel.basicReject(msg.getMessageProperties().getDeliveryTag(), false);
                } else {
                    channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, true);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
